<!DOCTYPE html>
<html>
<head>
<script src="../../../resources/js-test.js"></script>
<script src="../resources/common.js"></script>
<script src="../resources/picker-common.js"></script>
</head>
<body>
<select id="menu">
  <option selected>foo</option>
  <option>bar</option>
  <option hidden>baz</option>
  <optgroup label="qux">
      <option>garply</option>
  </optgroup>
</select>
<script>
var menuElement = document.getElementById('menu');
var picker;

function openPickerErrorCallback() {
    testFailed('picker didn\'t open')
    finishJSTest();
}
openPicker(menu, test1, openPickerErrorCallback);

function test1() {
    picker = internals.pagePopupWindow.global.picker;

    function onUpdate() {
        setTimeout(function() {
            shouldBeEqualToString('picker._selectElement.style.color', 'rgb(123, 0, 0)');
            shouldBeEqualToString('picker._selectElement.options[0].style.color', '');
            picker.removeListener("didUpdate", onUpdate);
            test2();
        });
    }
    picker.on("didUpdate", onUpdate);
    menuElement.style.color = 'rgb(123, 0, 0)';
}

function test2() {
    hoverOverElement(picker._selectElement.children[0]);
    shouldBeEqualToString('picker._selectElement.value', '0');
    eventSender.keyDown('ArrowDown');
    shouldBeEqualToString('picker._selectElement.value', '1');

    picker.on("didUpdate", onUpdate);
    menuElement.innerHTML = '<option>FOO</option><option>BAR</option><optgroup label="BAZ"></optgroup>';

    function onUpdate() {
        setTimeout(function() {
            shouldBeEqualToString('picker._selectElement.value', '1');
            shouldBe('picker._selectElement.options.length', '2');
            shouldBeEqualToString('picker._selectElement.children[0].label', 'FOO');
            shouldBeEqualToString('picker._selectElement.children[1].label', 'BAR');
            shouldBeEqualToString('picker._selectElement.children[2].tagName', 'OPTGROUP');
            shouldBeEqualToString('picker._selectElement.children[2].label', 'BAZ');
            picker.removeListener("didUpdate", onUpdate);
            test3();
        }, 0);
    };
}

function test3() {
    hoverOverElement(picker._selectElement.children[2]);
    shouldBeEqualToString('picker._selectElement.value', '1');

    menuElement.innerHTML = '<option>FOO</option><option>BAR</option><option selected>QUX</option>';

    picker.on("didUpdate", function () {
        setTimeout(function () {
            shouldBeEqualToString('picker._selectElement.value', '2');
            finishJSTest();
        }, 0);
    });
}
</script>
</body>
</html>
